let departmentaddModule = (function(){
    let $departmentName = $('.departmentName'),
        $departmentDesc = $('.departmentDesc'),
        $submit = $('.submit'),
        $spanName = $('.spanName'),
        $spanDesc = $('.spanDesc');
    let departmentId = null;
    // 获取 编辑的部门的信息
    async function getDepartmentInfo(){
        let result = await axios.get('/department/info',{
            params:{
                departmentId
            }
        })
        if(result.code == 0){
            bindHTML(result.data);
        }
        alert('小主，网络繁忙，请稍后重试');
        return;
    }
    // 根据获得的部门信息 动态渲染到表单中
    function bindHTML(data){
        $departmentName.val(data.name);
        $departmentDesc.val(data.desc);
    }
    // 表单校验
    function checkName(){
        if($departmentName.val().trim() === ''){
            $spanName.html('小主，部门名字不能为空！')
            return false;
        }else{
            $spanName.html('');
            return true;
        }
    }
    function handle(){
        $departmentName.blur(checkName);
        $submit.click(async e=>{
            if(!checkName()) return;
            let params = {
                name:$departmentName.val().trim(),
                desc:$departmentDesc.val().trim()
            }
            // 区分编辑 新增
            if(departmentId){
                params['departmentId'] = departmentId;
                let result = await axios.post('/department/update',params);
                if(result.code == 0){
                    alert('小主，您很棒，已成功为您修改一个部门信息~');
                    return;
                }
                alert('小主，网络繁忙，请稍后重试');
                return;

            }else{
                let result = await axios.post('/department/add',params);
                if(result.code == 0){
                    alert('小主，您很棒，已成功为您新增一个部门信息~');
                    return;
                }
                alert('小主，网络繁忙，请稍后重试');
                return;
            }
        })
    }
    return {
        init(){
            let params = window.location.href.queryUrlParams();// 获取问号传参的值
            if(params.departmentId){
                // 编辑页面
                departmentId = params.departmentId;
                getDepartmentInfo();
            }
            handle();
        }
    }
}())
departmentaddModule.init();